package com.jkoss.wine.merchant.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.UuidUtil;
import com.jkoss.wine.merchant.entity.MerchantProduct;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.mapper.MerchantProductMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductNormMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductTypeMapper;
import com.jkoss.wine.merchant.service.IMerchantProductService;
import com.jkoss.wine.shop.entity.InventoryWarning;
import com.jkoss.wine.shop.entity.MerchantProductPics;
import com.jkoss.wine.shop.entity.Product;
import com.jkoss.wine.shop.entity.ProductInventory;
import com.jkoss.wine.shop.entity.ProductNorm;
import com.jkoss.wine.shop.entity.ProductPics;
import com.jkoss.wine.shop.entity.ProductType;
import com.jkoss.wine.shop.entity.Shop;
import com.jkoss.wine.shop.mapper.InventoryWarningMapper;
import com.jkoss.wine.shop.mapper.MerchantProductPicsMapper;
import com.jkoss.wine.shop.mapper.ProductInventoryMapper;
import com.jkoss.wine.shop.mapper.ProductMapper;
import com.jkoss.wine.shop.mapper.ProductNormMapper;
import com.jkoss.wine.shop.mapper.ProductPicsMapper;
import com.jkoss.wine.shop.mapper.ProductTypeMapper;
import com.jkoss.wine.shop.mapper.ShopMapper;

/**
 * 服务实现类
 * 
 * @Author Ning
 * @Version 1.0, 2018-09-28
 * @See
 * @Since com.jkoss.mengal.merchant.service.impl
 * @Description: TODO
 */
@Service
public class MerchantProductServiceImpl extends ServiceImpl<MerchantProductMapper, MerchantProduct> implements IMerchantProductService {
	@Autowired
	private MerchantProductTypeMapper merchantProductTypeMapper;
	@Autowired
	private ShopMapper shopMapper;
	@Autowired
	private MerchantProductMapper merchantProductMapper;
	@Autowired
	private ProductTypeMapper productTypeMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private MerchantProductNormMapper merchantProductNormMapper;
	@Autowired
	private ProductNormMapper productNormMapper;
	@Autowired
	private ProductInventoryMapper productInventoryMapper;
	@Autowired
	private InventoryWarningMapper inventoryWarningMapper;
	@Autowired
	private MerchantProductPicsMapper merchantProductPicsMapper;
	@Autowired
	private ProductPicsMapper productPicsMapper;
	@Autowired
	private IMerchantProductService iMerchantProductService;

	@Override
	public boolean insertMerchantProduct(MerchantProduct entity, MerchantProductNorm merchantProductNorm, String[] shopAssetUrls) throws Exception {
		// region 检查数据有效性
		if (CommonUtil.isBlank(merchantProductTypeMapper.selectById(entity.getMerchantProductTypeId()))) {
			throw new Exception("商品类型有误");
		}
		// endregion

		List<Shop> shops = shopMapper.selectList(null);

		// region 插入总店商品数据
		// String merchantProductId = UuidUtil.getUUID();
		Date now = new Date();
		MerchantProduct merchantProduct = new MerchantProduct();
		BeanUtils.copyProperties(entity, merchantProduct);
		// merchantProduct.setMerchantProductId(merchantProductId);
		merchantProduct.setAddTime(CommonUtil.getDate());
		merchantProduct.setMerchantProductTypeId(entity.getMerchantProductTypeId());
		if (!retBool(merchantProductMapper.insert(merchantProduct))) {
			throw new Exception("新增商品失败");
		}
		// endregion

		Wrapper ptWrapper = Condition.create().eq("parent_id", merchantProduct.getMerchantProductTypeId());
		List<ProductType> productTypes = productTypeMapper.selectList(ptWrapper);
		Map<String, String> productTypesIds = new HashMap<>();
		for (ProductType productType : productTypes) {
			productTypesIds.put(productType.getShopId(), productType.getProductTypeId());
		}
		List<Product> products = new ArrayList<>();
		// region 插入分店商品数据
		for (Shop shop : shops) {
			String typeId = productTypesIds.get(shop.getShopId());
			if (typeId != null) {
				Product product = new Product();
				BeanUtils.copyProperties(merchantProduct, product);
				product.setParentId(merchantProduct.getMerchantProductId());
				product.setProductId(UuidUtil.getUUID());
				product.setShopId(shop.getShopId());
				product.setProductTypeId(typeId);
				product.setFreightPrice(0);
				product.setDel(0);
				products.add(product);
			}

		}
		if (products.size() > 0) {
			productMapper.insertBatch(products);
		}
		// endregion

		// region 插入商品规格
		// MerchantProductNorm vo = new MerchantProductNorm();
		merchantProductNorm.setNormName(merchantProduct.getProductName());
		merchantProductNorm.setNormPicUrl(merchantProduct.getShopAssetUrl());
		merchantProductNorm.setSorting(0);
		merchantProductNorm.setOperator(merchantProduct.getOperator());
		merchantProductNorm.setMerchantProductId(merchantProduct.getMerchantProductId());
		// vo.setProductNum(merchantProductNorm.getProductNum());
		// vo.setPrimeCostsPrice(entity.getPrimeCostsPrice);
		// vo.setSuggestedPrice(entity.getSuggestedPrice);
		merchantProductNorm.setDel(0);
		Wrapper mpnWrapper = Condition.create().eq("norm_name", merchantProductNorm.getNormName());
		int i = merchantProductNormMapper.selectCount(mpnWrapper);
		if (i > 0) {
			throw new Exception("名称已经存在");
		}
		Wrapper mpnNumWrapper = Condition.create().ne("del", 1).eq("product_num", merchantProductNorm.getProductNum());
		if (merchantProductNormMapper.selectCount(mpnNumWrapper) > 0) {
			throw new Exception("该条形码已经被使用");
		}

		// String merchantProductNormId = IdHelper.create();
		BeanUtils.copyProperties(merchantProductNorm, merchantProductNorm);
		// merchantProductNorm.setMerchantProductNormId(merchantProductNormId);
		merchantProductNorm.setAddTime(CommonUtil.getDate());
		if (!retBool(merchantProductNormMapper.insert(merchantProductNorm))) {
			throw new Exception("商品规格添加失败");
		}

		List<ProductNorm> shopProductNorm = new ArrayList<>();

		// region 获取各个店铺下的productID
		Wrapper pWrapper = Condition.create().eq("parent_id", merchantProductNorm.getMerchantProductId());
		List<Product> productSelect = productMapper.selectList(pWrapper);
		Map<String, String> productIds = new HashMap<>();
		for (Product product : productSelect) {
			productIds.put(product.getShopId(), product.getProductId());
		}
		// endregion
		for (Shop shop : shops) {
			String productId = productIds.get(shop.getShopId());
			if (productId != null) {
				ProductNorm productNorm = new ProductNorm();
				BeanUtils.copyProperties(merchantProductNorm, productNorm);
				productNorm.setSorting(0);
				productNorm.setProductNormId(UuidUtil.getUUID());
				productNorm.setShopId(shop.getShopId());
				productNorm.setProductId(productId);
				productNorm.setDel(0);
				productNorm.setNormPrice(merchantProductNorm.getSuggestedPrice());
				productNorm.setParentId(merchantProductNorm.getMerchantProductNormId());
				productNorm.setNormPicUrl(merchantProductNorm.getNormPicUrl());
				shopProductNorm.add(productNorm);
			}
		}
		if (shopProductNorm.size() > 0) {
			if (!retBool(productNormMapper.insertBatch(shopProductNorm))) {
				throw new Exception("门店商品规格添加失败");
			}
		}
		// // region 添加库存
		// List<ProductInventory> productInventories = new ArrayList<>();
		// for (ProductNorm productNorm : shopProductNorm) {
		// ProductInventory temp = new ProductInventory();
		// temp.setProductInventoryId(UuidUtil.getUUID());
		// temp.setProductId(productNorm.getProductId());
		// temp.setProductNormId(productNorm.getProductNormId());
		// temp.setShopId(productNorm.getShopId());
		// temp.setInventoryNum(null);
		// temp.setBasketId(null);
		// temp.setInventory(0);
		// temp.setType(0);
		// temp.setOperator(merchantProductNorm.getOperator());
		// temp.setAddTime(CommonUtil.getDate());
		// temp.setRemark("创建商品自动入库");
		// productInventories.add(temp);
		// }
		// if (productInventories.size() > 0) {
		// if (!retBool(productInventoryMapper.insertBatch(productInventories))) {
		// throw new Exception("创建商品自动入库失败");
		// }
		// }
		// endregion

		// region 插入总店库存
		// TODO: 2018/5/21 第一期总店暂时没有库存
		// endregion

		// region 插入库存
		Wrapper pnWrapper = Condition.create().eq("parent_id", merchantProductNorm.getMerchantProductNormId());
		List<ProductNorm> productNorms = productNormMapper.selectList(pnWrapper);
		List<ProductInventory> inventories = new ArrayList<>();
		for (ProductNorm productNorm : productNorms) {
			ProductInventory temp = new ProductInventory();
			temp.setProductInventoryId(UuidUtil.getUUID());
			temp.setProductId(productNorm.getProductId());
			temp.setProductNormId(productNorm.getProductNormId());
			temp.setShopId(productNorm.getShopId());
			temp.setInventory(0);
			temp.setType(0);
			temp.setOperator(merchantProduct.getOperator());
			temp.setAddTime(CommonUtil.getDate());
			temp.setRemark("创建商品自动入库");
			temp.setInventoryNum(null);
			temp.setBasketId(null);
			inventories.add(temp);
		}
		if (inventories.size() > 0) {
			if (!retBool(productInventoryMapper.insertBatch(inventories))) {
				throw new Exception("创建商品自动入库失败");
			}
		}
		// endregion

		// region 插入分商店库存预警信息
		List<InventoryWarning> inventoryWarnings = new ArrayList<>();
		for (ProductNorm productNorm : productNorms) {
			InventoryWarning inventoryWarning = new InventoryWarning();
			inventoryWarning.setInventoryWarningId(UuidUtil.getUUID());
			inventoryWarning.setAddTime(now);
			inventoryWarning.setWarningValue(0);
			inventoryWarning.setOperator(merchantProduct.getOperator());
			inventoryWarning.setProductNormId(productNorm.getProductNormId());
			inventoryWarning.setProductId(productNorm.getProductId());
			inventoryWarning.setShopId(productNorm.getShopId());
			inventoryWarnings.add(inventoryWarning);
		}
		if (inventoryWarnings.size() > 0) {
			if (!retBool(inventoryWarningMapper.insertBatch(inventoryWarnings))) {
				throw new Exception("门店商品库存预警信息失败");
			}
		}
		// endregion

		// region 插入商品图列表
		List<MerchantProductPics> merchantProductPics = new ArrayList<>();
		if (shopAssetUrls != null && shopAssetUrls.length > 0) {
			// 防止图片重复导致报错
			List<String> productPics = Arrays.asList(shopAssetUrls);
			// merchantProductPics.addAll(createMerchantProductPics(entity.getMerchantProductId(),
			// productPics));
			// List<MerchantProductPics> picsList = new ArrayList<>();
			// for (String assetUrl : productPics) {
			// MerchantProductPics pic = new MerchantProductPics();
			// pic.setMerchantProductId(merchantProduct.getMerchantProductId());
			// pic.setMerchantAssetUrl(assetUrl);
			// picsList.add(pic);
			// }
			List<MerchantProductPics> picsList = createMerchantProductPics(merchantProduct.getMerchantProductId(), productPics);
			merchantProductPics.addAll(picsList);
			if (!retBool(merchantProductPicsMapper.insertBatch(merchantProductPics))) {
				throw new Exception("总店商品图列表失败");
			}
		}
		// endregion

		// region 插入分店商品图列表
		List<ProductPics> productPics = new ArrayList<>();
		for (Product product : products) {
			for (MerchantProductPics merchantProductPic : merchantProductPics) {
				ProductPics pics = new ProductPics();
				pics.setProductId(product.getProductId());
				pics.setShopAssetUrl(merchantProductPic.getMerchantAssetUrl());
				pics.setParentId(merchantProductPic.getMerchantProductId());
				productPics.add(pics);
			}
		}
		if (productPics.size() > 0) {
			if (!retBool(productPicsMapper.insertBatch(productPics))) {
				throw new Exception("门店商品图列表失败");
			}
		}
		// endregion
		return true;
	}

	@Override
	public boolean updateMerchantProduct(MerchantProduct vo, MerchantProductNorm merchantProductNorm, String[] shopAssetUrls) throws Exception {
		// region 检查数据有效性
		if (merchantProductTypeMapper.selectById(vo.getMerchantProductTypeId()) == null) {
			throw new Exception("商品类型有误");
		}
		// endregion

		// region 插入商品数据
		String merchantProductId = vo.getMerchantProductId();
		MerchantProduct merchantProduct = new MerchantProduct();
		BeanUtils.copyProperties(vo, merchantProduct);
		merchantProduct.setMerchantProductId(merchantProductId);
		merchantProduct.setMerchantProductTypeId(vo.getMerchantProductTypeId());
		int i = merchantProductMapper.updateById(merchantProduct);
		if (i != 1) {
			throw new Exception("更新商品信息失败");
		}
		// endregion

		Wrapper ptWrapper = Condition.create().eq("parent_id", vo.getMerchantProductTypeId());
		List<ProductType> productTypes = productTypeMapper.selectList(ptWrapper);
		Wrapper pWrapper = Condition.create().eq("parent_id", merchantProductId);
		List<Product> products = productMapper.selectList(pWrapper);
		for (Product product : products) {
			BeanUtils.copyProperties(vo, product, "productId", "productTypeId");
			// product的productTypeId选择后需要重新改成对应的productTypeId
			for (ProductType productType : productTypes) {
				if (productType.getShopId().equals(product.getShopId())) {
					product.setProductTypeId(productType.getProductTypeId());
				}
			}
		}
		productMapper.updateBatch(merchantProduct, products);

		// region 插入商品图列表
		// Example example = new Example(MerchantProductPics.class);
		// Example.Criteria criteria = example.createCriteria();
		// criteria.andEqualTo("merchantProductId", merchantProductId);
		// merchantProductPicsMapper.deleteByExample(example);
		Wrapper mppWrapper = Condition.create().eq("merchant_product_id", merchantProductId);
		merchantProductPicsMapper.delete(mppWrapper);
		if (shopAssetUrls != null && shopAssetUrls.length > 0) {
			List<String> merchantProductPics = Arrays.asList(shopAssetUrls);
			List<MerchantProductPics> picsList = createMerchantProductPics(merchantProductId, merchantProductPics);
			merchantProductPicsMapper.insertBatch(picsList);

		}
		// endregion

		// region 插入分店列表图
		// Example productPicsExample = new Example(ProductPics.class);
		// Example.Criteria productPicsCriteria = productPicsExample.createCriteria();
		// productPicsCriteria.andEqualTo("parentId", merchantProductId);
		// productPicsMapper.deleteByExample(productPicsExample);
		Wrapper ppsWrapper = Condition.create().eq("parent_id", merchantProductId);
		productPicsMapper.delete(ppsWrapper);
		if (shopAssetUrls != null && shopAssetUrls.length > 0) {
			List<String> productPics = Arrays.asList(shopAssetUrls);
			List<ProductPics> picsList = new ArrayList<>();
			for (String productPic : productPics) {
				for (Product product : products) {
					ProductPics temp = new ProductPics();
					temp.setShopAssetUrl(productPic);
					temp.setParentId(merchantProduct.getMerchantProductId());
					temp.setProductId(product.getProductId());
					picsList.add(temp);
				}
			}
			productPicsMapper.insertBatch(picsList);

		}

		// endregion
		return true;
	}

	/**
	 * 创建一个没有重复属性的ProductPics list
	 */
	private List<MerchantProductPics> createMerchantProductPics(String productId, List<String> productPicsUrl) {
		List<MerchantProductPics> picsList = new ArrayList<>();
		for (String assetUrl : productPicsUrl) {
			MerchantProductPics pic = new MerchantProductPics();
			pic.setMerchantProductId(productId);
			pic.setMerchantAssetUrl(assetUrl);
			picsList.add(pic);
		}
		return picsList;
	}

	@Override
	public Page selectVoByPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByPage(page, wrapper));
		return page;
	}
	
	@Override
    public boolean updateProductState(String id,MerchantProduct merchantProduct) throws Exception {
		merchantProduct = merchantProductMapper.selectById(id);
		int j =merchantProduct.getState();
		if (j==0) {
			merchantProduct.setState(1);
		} else {
			merchantProduct.setState(0);
		}
		int i = merchantProductMapper.updateAllColumnById(merchantProduct);
		if (i != 1) {
            throw new Exception("更新失败:找不到该条记录");
        }
		Product product = new Product();
		Wrapper wrapper = Condition.create().eq("parent_id", merchantProduct.getMerchantProductId());
		product.setParentId(merchantProduct.getMerchantProductId());
		product.setState(merchantProduct.getState());
		productMapper.update(product, wrapper);
		return true;
    }
}
